<?php

namespace App\Http\Controllers\Admin\Goods;

use App\B2BProject\Admin\AdminControllerBuildTrait;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\B2BProject\Custom\Business\GoodsCategory;

class CategoryController extends Controller
{
    use AdminControllerBuildTrait;

    protected $moduleName = '商品分类管理';

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        if (\Request::ajax()) {
            $data    = [];
            $parents = GoodsCategory::getGlobalCategory();
            foreach ($parents as $parent) {
                $item           = [
                    'id'          => $parent->id,
                    'name'        => $parent->name,
                    'sort'        => $parent->sort,
                    'new_href'    => route('admin.goods.category.create', ['parent_id' => $parent->id]),
                    'edit_href'   => route('admin.goods.category.edit', [$parent->id]),
                    'delete_href' => route('admin.goods.category.destroy', [$parent->id]),
                ];
                if($parent->children()->count()){
                    $item['hasChildren']=call_user_func_array(function ($par) {
                        foreach ($par as $child) {
                            $childs = [
                                'id'          => $child->id,
                                'name'        => $child->name,
                                'sort'        => $child->sort,
                                'edit_href'   => route('admin.goods.category.edit', [$child->id]),
                                'delete_href' => route('admin.goods.category.destroy', [$child->id]),
                            ];
                            $da[]   = $childs;
                        }
                        return $da;
                    }, [$parent->children]);
                }
                $data['data'][] = $item;
            }
            return response()->json($data);
        }
        return view('admin/goods/category/index');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request)
    {
        $parent_id  = $request->query('parent_id');
        return view('admin/goods/category/edit')->with('form', route('admin.goods.category')) ;
    }

    /**
     * 获取上级分类
     * @return \Illuminate\Http\JsonResponse
     */
    public function parent()
    {
        $all  = GoodsCategory::getGlobalCategory();
        $data = [];
        $data['data'][]=[
            'code' =>0,
            'text' =>'顶级分类',
        ];
        foreach ($all as $category) {
            $item           = [
                'code' => $category->id,
                'text' => $category->name,
            ];
            $data['data'][] = $item;
        }

        return response()->json($data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'name'      => 'required',
            'sort'      => 'numeric',
            'display'   => 'boolean',
            'parent_id' => 'required|numeric',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        $category = new GoodsCategory();

        $category->name    = $request->name;
        $category->sort    = $request->input('sort', 0);
        $category->display = $request->input('display', true);

        $category->save(); // 保存数据

        if (($parent_id = $request->input('parent_id')) > 0) {
            GoodsCategory::findOrFail($parent_id)->children()->save($category);
            $category->save();
        }

        return redirect()->route('admin.goods.category');
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        // 根据id查找分类信息
        $editTarget = GoodsCategory::findOrFail($id);

        $parent_id = GoodsCategory::where('id', $id)->first()->parent_id;
        $form      = route('admin.goods.category.update', [$editTarget->id]);

        return view('admin/goods/category/edit')->with('editTarget', $editTarget)->with('form',
            $form)->with('parent_id', $parent_id);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'name'      => 'required',
            'sort'      => 'numeric',
            'parent_id' => 'required|numeric',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        $data     = $request->only(['name', 'sort']);// 只取这些数据
        $category = GoodsCategory::findOrFail($id); //创建分类对象
        $category->update($data);

        if ($request->input('parent_id') == 0) {
            $category->parent_id = 0;
            $category->save(); // 保存数据
        } else {
            GoodsCategory::find($request->input('parent_id'))->children()->save($category);
        }

        return redirect()->route('admin.goods.category');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request, $id)
    {
        $category = GoodsCategory::findOrFail($id);
        $category->delete();

        return $this->index();
    }
}
